import store from '@/store'
import router from './router'

router.beforeEach(async(to, from, next) => {
  // 如果有token
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userInfo.userId) {
        await store.dispatch('user/getUserInfo')
        const menus = store.state.user.userInfo.roles.menus
        const routes = await store.dispatch('permission/FilterRouter', menus)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
        return
      }
      next()
    }
    // 如果没token
  } else {
    const ffflist = ['/login', '/404']
    if (ffflist.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
